package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.utils.DateUtils;
import com.atguigu.yygh.hosp.repository.ScheduleRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.BookingRule;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ScheduleServiceImpl  implements ScheduleService {

    @Autowired
    private  ScheduleService scheduleService;

//     Repository -->仓库
//     schedule  --> 清单
    @Autowired
    private ScheduleRepository scheduleRepository;

    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private MongoTemplate mongoTemplate;

//    保存排班信息
    @Override
    public void saveSchedule(Map<String, Object> scheduleParams) {

//        JSON转换为POJO类对象
        Schedule resultParam = JSONObject.parseObject(JSONObject.toJSONString(scheduleParams),Schedule.class);
        String hoscode = resultParam.getHoscode();
        String depcode = resultParam.getDepcode();
        String hosScheduleId = resultParam.getHosScheduleId();

//        根据医院信息 科室信息 和排班信息进行查询
        Schedule platformSchedule =  scheduleRepository
                .findByHoscodeAndDepcodeAndHosScheduleId(hoscode,depcode,hosScheduleId);
        if (platformSchedule == null){
//            对数据库创建对象
            resultParam.setCreateTime(new Date());
            resultParam.setUpdateTime(new Date());
            resultParam.setIsDeleted(0);
            scheduleRepository.save(resultParam);
        }else{
//            对数据库进行修改对象
            resultParam.setId(platformSchedule.getId());
            resultParam.setCreateTime(platformSchedule.getCreateTime());
            resultParam.setUpdateTime(new Date());
            resultParam.setIsDeleted(platformSchedule.getIsDeleted());
            scheduleRepository.save(resultParam);
        }


    }

//  按条件的分页查询
    @Override
    public Page<Schedule> getSchedulePage(Map<String, Object> scheduleParams) {
//        获取医院的Id
        Schedule schedule = new Schedule();
        String hoscode = (String) scheduleParams.get("hoscode");
        schedule.setHoscode(hoscode);

//        条件查询
        Example<Schedule> scheduleExample = Example.of(schedule);

//        获取pahe和llimit
        int pageNum = Integer.parseInt(scheduleParams.get("page").toString());
        int limit = Integer.parseInt(scheduleParams.get("limit").toString());
        PageRequest PageInfo = PageRequest.of(pageNum, limit, Sort.by("createTime").ascending());

        Page<Schedule> result = scheduleRepository.findAll(scheduleExample, PageInfo);
        return  result;
    }

//    删除排班信息
    @Override
    public void remove(Map<String, Object> scheduleParams) {
//        获取排班的Id  hosScheduleId
        Schedule schedule = new Schedule();
        String hoscode = (String) scheduleParams.get("hoscode");
        String hosScheduleId = (String) scheduleParams.get("hosScheduleId");

        Schedule resultObj = scheduleRepository.findByHoscodeAndHosScheduleId(hoscode,hosScheduleId);
       if (resultObj != null){
           scheduleRepository.deleteById(resultObj.getId());
       }

    }

//    查询科室的排版信息(右上角)
    @Override
    public Map<String, Object> getPage(Integer pageNum, Integer pageSize, String hoscode, String depcode) {
        Map<String, Object> result = new HashMap<>();

//        聚合 MongoTemplate :  普通的方式是 MongoRepository
//        聚合的条件
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),                                                //查询条件
                Aggregation.group("workDate")                                       //分组条件
                           .first("workDate").as("workDate")                //按照工作日期进行分组
                           .sum("reservedNumber").as("reservedNumber")      //可预约数的总和
                           .sum("availableNumber").as("availableNumber")    //不可预约数的总和
                           .count().as("docCount"),
                Aggregation.sort(Sort.Direction.ASC,"workDate"),
                Aggregation.skip((pageNum-1)*pageSize),
                Aggregation.limit(pageSize)
        ); //聚合条件

        /*
        *   第一个参数 aggregation : 表示聚合的条件
        *   第二个参数 InputType:    表示输入的类型,可以根据当前指定的字节码找到Mongo对应的集合
        *   第三个参数 OutPutType:   表示输出的类型,可以封装聚合后的信息
        * */
        AggregationResults<BookingScheduleRuleVo> aggregate = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
//        当且页的排班列表数据
        List<BookingScheduleRuleVo> mappedResults = aggregate.getMappedResults();
        for (BookingScheduleRuleVo mappedResult : mappedResults) {
            Date workDate = mappedResult.getWorkDate();
//            工具类 --> 把工作时间转化为周几
            String dayOfWeek = DateUtils.getDayOfWeek(new DateTime(workDate));
            mappedResult.setDayOfWeek(dayOfWeek);
        }

        result.put("list",mappedResults);
        Aggregation totalaggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),                                                //查询条件
                Aggregation.group("workDate")                                       //分组条件
        ); //聚合条件

        AggregationResults<BookingScheduleRuleVo> totalaggregate = mongoTemplate.aggregate(totalaggregation, Schedule.class, BookingScheduleRuleVo.class);
//        总记录数大小
        int total = totalaggregate.getMappedResults().size();
        result.put("total",total);


        //获取医院名称
        Hospital hospital = hospitalService.getHospitalByHoscode(hoscode);
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname",hospital.getHosname());
        result.put("baseMap",baseMap);
        return result;
    }

//    获取排班数据
    @Override
    public List<Schedule> detail(String hoscode, String depcode, Date workdate) {

        List<Schedule> scheduleList=scheduleRepository.findByHoscodeAndDepcodeAndWorkDate(hoscode,depcode,workdate);
        //把得到list集合遍历，向设置其他值：医院名称、科室名称、日期对应星期
        scheduleList.stream().forEach(this::packageSchedule);
        return scheduleList;
    }

    //    获取医院排班的信息(分页查询)
    @Override
    public Map<String, Object> getSchedulePageByCondition(String hoscode, String depcode, Integer pageNum, Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        //获取预约规则
        Hospital hospital = hospitalService.getHospitalByHoscode(hoscode);
        if(null == hospital) {
            throw new YyghException();
        }
        BookingRule bookingRule = hospital.getBookingRule();

        //获取可预约日期分页数据
        IPage iPage = this.getListDate(pageNum, pageSize, bookingRule);
        //当前页可预约日期
        List<Date> dateList = iPage.getRecords();
        //获取可预约日期科室剩余预约数
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode).and("workDate").in(dateList);
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")//分组字段
                        .first("workDate").as("workDate")
                        .count().as("docCount")
                        .sum("availableNumber").as("availableNumber")
                        .sum("reservedNumber").as("reservedNumber")
        );
        AggregationResults<BookingScheduleRuleVo> aggregationResults = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> scheduleVoList = aggregationResults.getMappedResults();
        //获取科室剩余预约数

        //合并数据 将统计数据ScheduleVo根据“安排日期”合并到BookingRuleVo
        Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(scheduleVoList)) {
            scheduleVoMap = scheduleVoList.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate, BookingScheduleRuleVo -> BookingScheduleRuleVo));
        }
        //获取可预约排班规则
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for(int i=0, len=dateList.size(); i<len; i++) {
            Date date = dateList.get(i);

            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
            if(null == bookingScheduleRuleVo) { // 说明当天没有排班医生
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //就诊医生人数
                bookingScheduleRuleVo.setDocCount(0);
                //科室剩余预约数  -1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            //计算当前预约日期为周几
            String dayOfWeek = DateUtils.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

            //最后一页最后一条记录为即将预约   状态 0：正常 1：即将放号 -1：当天已停止挂号
            if(i == len-1 && pageNum == iPage.getPages()) {
                bookingScheduleRuleVo.setStatus(1);
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }
            //当天预约如果过了停号时间， 不能预约
            if(i == 0 && pageNum == 1) {
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if(stopTime.isBeforeNow()) {
                    //停止预约
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }

        //可预约日期规则数据
        result.put("list", bookingScheduleRuleVoList);
        result.put("total", iPage.getTotal());
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalService.getHospitalByHoscode(hoscode).getHosname());
        //科室
        Department department =departmentService.getDepartment(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);
        return result;

    }

//    根据排班Id获取排班信息
    @Override
    public Schedule getScheduleInfo(String scheduleId) {
//        获取排班信息
        Schedule schedule = scheduleRepository.findById(scheduleId).get();
        Hospital byHoscode = hospitalService.getHospitalByHoscode(schedule.getHoscode());
        this.packageSchedule(schedule);
        schedule.setHoscode(byHoscode.getHosname());
        return schedule;
    }

//    根据排班Id获取排班信息(远程调用)
    @Override
    public ScheduleOrderVo getScheduleById(String scheduleId) {
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        //排班信息
        Schedule schedule = scheduleRepository.findById(scheduleId).get();
        if(null == schedule) {
            throw new YyghException();
        }

        //获取预约规则信息
        Hospital hospital = hospitalService.getHospitalByHoscode(schedule.getHoscode());
        if(null == hospital) {
            throw new YyghException();
        }
        BookingRule bookingRule = hospital.getBookingRule();
        if(null == bookingRule) {
            throw new YyghException();
        }

        scheduleOrderVo.setHoscode(schedule.getHoscode());
        scheduleOrderVo.setHosname(hospital.getHosname());
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(departmentService.getDepartment(schedule.getHoscode(), schedule.getDepcode()).getDepname());
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());

        //退号截止天数（如：就诊前一天为-1，当天为0）
        int quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());

        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(schedule.getWorkDate(), bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());
        return scheduleOrderVo;
    }

//    根据排班Id更新排班信息(MongDb 只可以获取到信息之后再进行修改,不可以像Mybatis_plus一样覆盖)
    @Override
    public boolean updateAvailableNumber(String scheduleId, Integer availableNumber) {
        Schedule schedule = scheduleRepository.findById(scheduleId).get();

        schedule.setAvailableNumber(availableNumber);
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);
        return true;
    }

    @Override
    public void update(Schedule schedule) {
        schedule.setUpdateTime(new Date());
//        主键一直更新
        scheduleRepository.save(schedule);
    }

//    取消预约
    @Override
    public void cancelSchedule(String scheduleId) {
       Schedule schedule = scheduleRepository.findByHosScheduleId(scheduleId);
       schedule.setAvailableNumber(schedule.getAvailableNumber()+1);
       scheduleRepository.save(schedule);

    }


    //        获取可预约日期的分页数据
    private IPage<Date> getListDate(Integer pageNum, Integer pageSize, BookingRule bookingRule) {
        Integer cycle = bookingRule.getCycle();
//        此时此刻是否超过了医院规定当前的挂 号起始时间,如果已经超过了 cycle +1
        String releaseTime = bookingRule.getReleaseTime();

//        今天医院规定的医院挂号的起始时间 2024-02-04 9:28
        DateTime datetime = this.getDateTime(new Date(), releaseTime);
        if (datetime.isBeforeNow()){
            cycle= cycle+1;
        }

//        预约周期内所有的时间列表
         List<Date> list = new ArrayList<>();
        for (Integer i = 0; i < cycle; i++) {
            Date date = new DateTime(new DateTime().plusDays(i).toString("yyyy-MM-dd")).toDate();
            list.add(date);
        }
        int start = (pageNum-1)*pageSize;
        int end = start + pageSize;
        if (end>list.size()){
            end =list.size();
        }
        List<Date> currentPageDateList = new ArrayList<>();
        for (int j = start; j < end; j++) {
            Date date = list.get(j);
            currentPageDateList.add(date);
        }

        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Date> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNum, pageSize, list.size());
        page.setRecords(currentPageDateList);
        return page;
    }

    /*
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " "+ timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }

    private void packageSchedule(Schedule schedule) {
        //设置医院名称
        schedule.getParam().put("hosname",hospitalService.getHospitalByHoscode(schedule.getHoscode()));
        //设置科室名称
        schedule.getParam().put("depname",departmentService.getDepName(schedule.getHoscode(),schedule.getDepcode()));
        String dayOfWeek = DateUtils.getDayOfWeek(new DateTime(schedule.getWorkDate()));
        //设置日期对应星期
        schedule.getParam().put("dayOfWeek",dayOfWeek);
    }

}
